/*
 * Wazuh Vulnerability Scanner - Unit Tests
 * Copyright (C) 2015, Wazuh Inc.
 * October 3, 2023.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#include "updateCVEDescription_test.hpp"
#include "databaseFeedManager/databaseFeedManager.hpp"
#include "databaseFeedManager/updateCVEDescription.hpp"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/verifier.h"
#include "rocksDBWrapper.hpp"

namespace NSUpdateCVEDescriptionTest
{
    const char* INCLUDE_DIRECTORIES[] = {FLATBUFFER_SCHEMAS_DIR, nullptr};

    const std::string CVE5_FLATBUFFER_SCHEMA_PATH {FLATBUFFER_SCHEMAS_DIR "/cve5.fbs"};
    const std::string VULN_REM_FLATBUFFER_SCHEMA_PATH {FLATBUFFER_SCHEMAS_DIR "/vulnerabilityRemediations.fbs"};

    const std::string CVE_JSON_STR_CVSS_V3_1 {"CVE-2022-0605"};
    const std::string JSON_STR_CVSS_V3_1 {
        R"({
                    "containers": {
                        "cna": {
                        "affected": [
                            {
                            "cpes": [
                                "cpe:2.3:a:google:chrome:*:*:*:*:*:*:*:*"
                            ],
                            "defaultStatus": "unaffected",
                            "product": "chrome",
                            "vendor": "google",
                            "versions": [
                                {
                                "lessThan": "98.0.4758.102",
                                "status": "affected",
                                "version": "0",
                                "versionType": "custom"
                                }
                            ]
                            }
                        ],
                        "descriptions": [
                            {
                            "lang": "en",
                            "value": "Use after free in Webstore API in Google Chrome prior to 98.0.4758.102 allowed an attacker who convinced a user to install a malicious extension and convinced a user to enage in specific user interaction to potentially exploit heap corruption via a crafted HTML page."
                            }
                        ],
                        "metrics": [
                            {
                            "cvssV3_1": {
                                "attackComplexity": "LOW",
                                "attackVector": "NETWORK",
                                "availabilityImpact": "HIGH",
                                "baseScore": 8.8,
                                "baseSeverity": "HIGH",
                                "confidentialityImpact": "HIGH",
                                "integrityImpact": "HIGH",
                                "privilegesRequired": "NONE",
                                "scope": "UNCHANGED",
                                "userInteraction": "REQUIRED",
                                "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H",
                                "version": "3.1"
                            },
                            "format": "CVSS"
                            },
                            {
                            "cvssV2_0": {
                                "accessComplexity": "MEDIUM",
                                "accessVector": "NETWORK",
                                "authentication": "NONE",
                                "availabilityImpact": "PARTIAL",
                                "baseScore": 6.8,
                                "confidentialityImpact": "PARTIAL",
                                "integrityImpact": "PARTIAL",
                                "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P",
                                "version": "2.0"
                            },
                            "format": "CVSS"
                            }
                        ],
                        "problemTypes": [
                            {
                            "descriptions": [
                                {
                                "description": "CWE-416",
                                "lang": "en"
                                }
                            ]
                            }
                        ],
                        "providerMetadata": {
                            "orgId": "00000000-0000-4000-A000-000000000003",
                            "shortName": "nvd",
                            "dateUpdated": "2022-04-11T09:33:00Z"
                        },
                        "references": [
                            {
                            "name": "https://crbug.com/1286940",
                            "tags": [
                                "issue-tracking",
                                "permissions-required",
                                "vendor-advisory"
                            ],
                            "url": "https://crbug.com/1286940"
                            },
                            {
                            "name": "https://chromereleases.googleblog.com/2022/02/stable-channel-update-for-desktop_14.html",
                            "tags": [
                                "release-notes",
                                "vendor-advisory"
                            ],
                            "url": "https://chromereleases.googleblog.com/2022/02/stable-channel-update-for-desktop_14.html"
                            }
                        ]
                        }
                    },
                    "cveMetadata": {
                        "assignerOrgId": "00000000-0000-4000-A000-000000000003",
                        "assignerShortName": "nvd",
                        "cveId": "CVE-2022-0605",
                        "datePublished": "2022-04-05T00:15:00Z",
                        "dateUpdated": "2022-04-11T09:33:00Z",
                        "state": "PUBLISHED"
                    },
                    "dataType": "CVE_RECORD",
                    "dataVersion": "5.0"
    })"};

    const std::string CVE_JSON_STR_CVSS_V3_0 {"CVE-2019-0029"};
    const std::string JSON_STR_CVSS_V3_0 {
        R"({
                "containers": {
                    "cna": {
                        "affected": [
                            {
                                "cpes": [
                                    "cpe:2.3:o:juniper:advanced_threat_prevention:*:*:*:*:*:*:*:*"
                                ],
                                "defaultStatus": "unaffected",
                                "platforms": [
                                    "cpe:2.3:h:juniper:atp700:-:*:*:*:*:*:*:*",
                                    "cpe:2.3:h:juniper:atp400:-:*:*:*:*:*:*:*"
                                ],
                                "product": "advanced_threat_prevention",
                                "vendor": "juniper",
                                "versions": [
                                    {
                                        "lessThan": "5.0.3",
                                        "status": "affected",
                                        "version": "5.0.0",
                                        "versionType": "custom"
                                    }
                                ]
                            }
                        ],
                        "descriptions": [
                            {
                                "lang": "en",
                                "value": "Juniper ATP Series Splunk credentials are logged in a file readable by authenticated local users. Using these credentials an attacker can access the Splunk server. This issue affects Juniper ATP 5.0 versions prior to 5.0.3."
                            }
                        ],
                        "metrics": [
                            {
                                "cvssV3_0": {
                                    "attackComplexity": "LOW",
                                    "attackVector": "LOCAL",
                                    "availabilityImpact": "HIGH",
                                    "baseScore": 7.8,
                                    "baseSeverity": "HIGH",
                                    "confidentialityImpact": "HIGH",
                                    "integrityImpact": "HIGH",
                                    "privilegesRequired": "LOW",
                                    "scope": "UNCHANGED",
                                    "userInteraction": "NONE",
                                    "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
                                    "version": "3.0"
                                },
                                "format": "CVSS"
                            },
                            {
                                "cvssV2_0": {
                                    "accessComplexity": "LOW",
                                    "accessVector": "LOCAL",
                                    "authentication": "NONE",
                                    "availabilityImpact": "NONE",
                                    "baseScore": 2.1,
                                    "confidentialityImpact": "PARTIAL",
                                    "integrityImpact": "NONE",
                                    "vectorString": "AV:L/AC:L/Au:N/C:P/I:N/A:N",
                                    "version": "2.0"
                                },
                                "format": "CVSS"
                            }
                        ],
                        "problemTypes": [
                            {
                                "descriptions": [
                                    {
                                        "description": "CWE-532",
                                        "lang": "en"
                                    }
                                ]
                            }
                        ],
                        "providerMetadata": {
                            "orgId": "00000000-0000-4000-A000-000000000003",
                            "shortName": "nvd",
                            "dateUpdated": "2020-08-24T17:37:00Z"
                        },
                        "references": [
                            {
                                "name": "https://kb.juniper.net/JSA10918",
                                "tags": [
                                    "vendor-advisory"
                                ],
                                "url": "https://kb.juniper.net/JSA10918"
                            }
                        ]
                    }
                },
                "cveMetadata": {
                    "assignerOrgId": "00000000-0000-4000-A000-000000000003",
                    "assignerShortName": "nvd",
                    "cveId": "CVE-2019-0029",
                    "datePublished": "2019-01-15T21:29:00Z",
                    "dateUpdated": "2020-08-24T17:37:00Z",
                    "state": "PUBLISHED"
                },
                "dataType": "CVE_RECORD",
                "dataVersion": "5.0"
            })"};

    const std::string CVE_JSON_STR_CVSS_V2_0 {"CVE-2022-24753"};
    const std::string JSON_STR_CVSS_V2_0 {
        R"(        {
                "containers": {
                    "cna": {
                        "affected": [
                            {
                                "cpes": [
                                    "cpe:2.3:a:stripe:stripe_cli:*:*:*:*:*:*:*:*"
                                ],
                                "defaultStatus": "unaffected",
                                "platforms": [
                                    "cpe:2.3:o:microsoft:windows:-:*:*:*:*:*:*:*"
                                ],
                                "product": "stripe_cli",
                                "vendor": "stripe",
                                "versions": [
                                    {
                                        "lessThan": "1.7.13",
                                        "status": "affected",
                                        "version": "0",
                                        "versionType": "custom"
                                    }
                                ]
                            }
                        ],
                        "descriptions": [
                            {
                                "lang": "en",
                                "value": "Stripe CLI is a command-line tool for the Stripe eCommerce platform. A vulnerability in Stripe CLI exists on Windows when certain commands are run in a directory where an attacker has planted files. The commands are `stripe login`, `stripe config -e`, `stripe community`, and `stripe open`. MacOS and Linux are unaffected. An attacker who successfully exploits the vulnerability can run arbitrary code in the context of the current user. The update addresses the vulnerability by throwing an error in these situations before the code can run.Users are advised to upgrade to version 1.7.13. There are no known workarounds for this issue."
                            }
                        ],
                        "metrics": [
                            {
                                "cvssV2_0": {
                                    "accessComplexity": "MEDIUM",
                                    "accessVector": "LOCAL",
                                    "authentication": "NONE",
                                    "availabilityImpact": "PARTIAL",
                                    "baseScore": 4.4,
                                    "confidentialityImpact": "PARTIAL",
                                    "integrityImpact": "PARTIAL",
                                    "vectorString": "AV:L/AC:M/Au:N/C:P/I:P/A:P",
                                    "version": "2.0"
                                },
                                "format": "CVSS"
                            }
                        ],
                        "problemTypes": [
                            {
                                "descriptions": [
                                    {
                                        "description": "NVD-CWE-noinfo",
                                        "lang": "en"
                                    }
                                ]
                            }
                        ],
                        "providerMetadata": {
                            "orgId": "00000000-0000-4000-A000-000000000003",
                            "shortName": "nvd",
                            "dateUpdated": "2022-03-12T02:51:00Z"
                        },
                        "references": [
                            {
                                "name": "https://github.com/stripe/stripe-cli/commit/be38da5c0191adb77f661f769ffff2fbc7ddf6cd",
                                "tags": [
                                    "patch",
                                    "third-party-advisory"
                                ],
                                "url": "https://github.com/stripe/stripe-cli/commit/be38da5c0191adb77f661f769ffff2fbc7ddf6cd"
                            },
                            {
                                "name": "https://github.com/stripe/stripe-cli/security/advisories/GHSA-4cx6-fj7j-pjx9",
                                "tags": [
                                    "third-party-advisory"
                                ],
                                "url": "https://github.com/stripe/stripe-cli/security/advisories/GHSA-4cx6-fj7j-pjx9"
                            }
                        ]
                    }
                },
                "cveMetadata": {
                    "assignerOrgId": "00000000-0000-4000-A000-000000000003",
                    "assignerShortName": "nvd",
                    "cveId": "CVE-2022-24753",
                    "datePublished": "2022-03-09T23:15:00Z",
                    "dateUpdated": "2022-03-12T02:51:00Z",
                    "state": "PUBLISHED"
                },
                "dataType": "CVE_RECORD",
                "dataVersion": "5.0"
            })"};

    const std::string CVE_JSON_STR_MISSING_METRICS {"CVE-2022-1154"};
    const std::string JSON_STR_MISSING_METRICS {
        R"({
                    "containers": {
                        "cna": {
                        "affected": [
                            {
                            "defaultStatus": "unaffected",
                            "product": "vim",
                            "vendor": "arch",
                            "versions": [
                                {
                                "lessThan": "8.2.4651-1",
                                "status": "affected",
                                "version": "8.2.4464-1",
                                "versionType": "custom"
                                }
                            ]
                            },
                            {
                            "defaultStatus": "unaffected",
                            "product": "gvim",
                            "vendor": "arch",
                            "versions": [
                                {
                                "lessThan": "8.2.4651-1",
                                "status": "affected",
                                "version": "8.2.4464-1",
                                "versionType": "custom"
                                }
                            ]
                            }
                        ],
                        "providerMetadata": {
                            "orgId": "00000000-0000-4000-A000-000000000002",
                            "shortName": "arch"
                        },
                        "references": [
                            {
                            "url": "https://security.archlinux.org/CVE-2022-1154"
                            }
                        ],
                        "descriptions": [
                            {
                            "lang": "en",
                            "value": "not defined"
                            }
                        ]
                        }
                    },
                    "cveMetadata": {
                        "assignerOrgId": "00000000-0000-4000-A000-000000000002",
                        "assignerShortName": "arch",
                        "cveId": "CVE-2022-1154",
                        "state": "PUBLISHED"
                    },
                    "dataType": "CVE_RECORD",
                    "dataVersion": "5.0"
    })"};

    const std::string CVE_JSON_STR_REJECTED_CVE {"CVE-2012-6177"};
    const std::string JSON_STR_REJECTED_CVE {
        R"(
                {
                    "containers": {
                        "cna": {
                            "providerMetadata": {
                                "orgId": "00000000-0000-4000-A000-000000000003",
                                "shortName": "nvd",
                                "dateUpdated": "2017-05-11T14:29:20Z"
                            },
                            "rejectedReasons": [
                                {
                                "lang": "en",
                                "value": "** REJECT **  DO NOT USE THIS CANDIDATE NUMBER. ConsultIDs: none. Reason: The CNA or individual who requested this candidate did not associate it with any vulnerability during 2012. Notes: none."
                                }
                            ]
                        }
                    },
                    "cveMetadata": {
                        "cveId": "CVE-2012-6177",
                        "assignerOrgId": "00000000-0000-4000-A000-000000000003",
                        "assignerShortName": "nvd",
                        "dateUpdated": "2017-05-11T14:29:20Z",
                        "datePublished": "2017-05-11T14:29:20Z",
                        "state": "REJECTED"
                    },
                    "dataType": "CVE_RECORD",
                    "dataVersion": "5.0"
                })"};
} // namespace NSUpdateCVEDescriptionTest

using namespace NSUpdateCVEDescriptionTest;

TEST_F(UpdateCVEDescriptionTest, StoreCVEDescriptionCVSSV3_1)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_CVSS_V3_1.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_CVSS_V3_1.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    ASSERT_TRUE(rocksDBWrapper->get(CVE_JSON_STR_CVSS_V3_1, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));

    // Verify flatbuffer.
    flatbuffers::Verifier verifierVulnDesc(reinterpret_cast<const uint8_t*>(vulnerabilityDescriptionFBStr.c_str()),
                                           vulnerabilityDescriptionFBStr.size());
    EXPECT_EQ(NSVulnerabilityScanner::VerifyVulnerabilityDescriptionBuffer(verifierVulnDesc), true);

    // Read flatbuffer values.
    auto vulnerabilityDescription =
        NSVulnerabilityScanner::GetVulnerabilityDescription(vulnerabilityDescriptionFBStr.c_str());

    EXPECT_EQ(vulnerabilityDescription->scoreVersion()->str(), "3.1");
    EXPECT_EQ(vulnerabilityDescription->severity()->str(), "HIGH");
    EXPECT_EQ(vulnerabilityDescription->scoreBase(), (float)8.8);
    EXPECT_EQ(vulnerabilityDescription->description()->str(),
              "Use after free in Webstore API in Google Chrome prior to 98.0.4758.102 allowed an attacker who "
              "convinced a user to install a malicious extension and convinced a user to enage in specific user "
              "interaction to potentially exploit heap corruption via a crafted HTML page.");
    EXPECT_EQ(vulnerabilityDescription->classification()->str(), "CVSS");
    EXPECT_EQ(vulnerabilityDescription->reference()->str(),
              "https://crbug.com/1286940, "
              "https://chromereleases.googleblog.com/2022/02/stable-channel-update-for-desktop_14.html");
}

TEST_F(UpdateCVEDescriptionTest, StoreCVEDescriptionCVSSV3_0)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_CVSS_V3_0.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_CVSS_V3_0.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    ASSERT_TRUE(rocksDBWrapper->get(CVE_JSON_STR_CVSS_V3_0, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));

    // Verify flatbuffer.
    flatbuffers::Verifier verifierVulnDesc(reinterpret_cast<const uint8_t*>(vulnerabilityDescriptionFBStr.c_str()),
                                           vulnerabilityDescriptionFBStr.size());
    EXPECT_EQ(NSVulnerabilityScanner::VerifyVulnerabilityDescriptionBuffer(verifierVulnDesc), true);

    // Read flatbuffer values.
    auto vulnerabilityDescription =
        NSVulnerabilityScanner::GetVulnerabilityDescription(vulnerabilityDescriptionFBStr.c_str());

    EXPECT_EQ(vulnerabilityDescription->scoreVersion()->str(), "3.0");
    EXPECT_EQ(vulnerabilityDescription->severity()->str(), "HIGH");
    EXPECT_EQ(vulnerabilityDescription->scoreBase(), (float)7.8);
    EXPECT_EQ(vulnerabilityDescription->description()->str(),
              "Juniper ATP Series Splunk credentials are logged in a file readable by authenticated local users. Using "
              "these credentials an attacker can access the Splunk server. This issue affects Juniper ATP 5.0 versions "
              "prior to 5.0.3.");
    EXPECT_EQ(vulnerabilityDescription->classification()->str(), "CVSS");
    EXPECT_EQ(vulnerabilityDescription->reference()->str(), "https://kb.juniper.net/JSA10918");
}

TEST_F(UpdateCVEDescriptionTest, StoreCVEDescriptionCVSSV2_0)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_CVSS_V2_0.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_CVSS_V2_0.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    ASSERT_TRUE(rocksDBWrapper->get(CVE_JSON_STR_CVSS_V2_0, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));

    // Verify flatbuffer.
    flatbuffers::Verifier verifierVulnDesc(reinterpret_cast<const uint8_t*>(vulnerabilityDescriptionFBStr.c_str()),
                                           vulnerabilityDescriptionFBStr.size());
    EXPECT_EQ(NSVulnerabilityScanner::VerifyVulnerabilityDescriptionBuffer(verifierVulnDesc), true);

    // Read flatbuffer values.
    auto vulnerabilityDescription =
        NSVulnerabilityScanner::GetVulnerabilityDescription(vulnerabilityDescriptionFBStr.c_str());

    EXPECT_EQ(vulnerabilityDescription->scoreVersion()->str(), "2.0");
    EXPECT_EQ(vulnerabilityDescription->severity()->str(), "MEDIUM");
    EXPECT_EQ(vulnerabilityDescription->scoreBase(), (float)4.4);
    EXPECT_EQ(
        vulnerabilityDescription->description()->str(),
        "Stripe CLI is a command-line tool for the Stripe eCommerce platform. A vulnerability in Stripe CLI exists on "
        "Windows when certain commands are run in a directory where an attacker has planted files. The commands are "
        "`stripe login`, `stripe config -e`, `stripe community`, and `stripe open`. MacOS and Linux are unaffected. An "
        "attacker who successfully exploits the vulnerability can run arbitrary code in the context of the current "
        "user. The update addresses the vulnerability by throwing an error in these situations before the code can "
        "run.Users are advised to upgrade to version 1.7.13. There are no known workarounds for this issue.");
    EXPECT_EQ(vulnerabilityDescription->classification()->str(), "CVSS");
    EXPECT_EQ(vulnerabilityDescription->reference()->str(),
              "https://github.com/stripe/stripe-cli/commit/be38da5c0191adb77f661f769ffff2fbc7ddf6cd, "
              "https://github.com/stripe/stripe-cli/security/advisories/GHSA-4cx6-fj7j-pjx9");
}

TEST_F(UpdateCVEDescriptionTest, StoreCVEDescriptionMissingMetrics)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_MISSING_METRICS.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_MISSING_METRICS.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    ASSERT_TRUE(rocksDBWrapper->get(CVE_JSON_STR_MISSING_METRICS, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));

    // Verify flatbuffer.
    flatbuffers::Verifier verifierVulnDesc(reinterpret_cast<const uint8_t*>(vulnerabilityDescriptionFBStr.c_str()),
                                           vulnerabilityDescriptionFBStr.size());
    EXPECT_EQ(NSVulnerabilityScanner::VerifyVulnerabilityDescriptionBuffer(verifierVulnDesc), true);

    // Read flatbuffer values.
    auto vulnerabilityDescription =
        NSVulnerabilityScanner::GetVulnerabilityDescription(vulnerabilityDescriptionFBStr.c_str());

    EXPECT_EQ(vulnerabilityDescription->scoreVersion()->str(), "");
    EXPECT_EQ(vulnerabilityDescription->severity()->str(), "");
    EXPECT_EQ(vulnerabilityDescription->scoreBase(), 0);
    EXPECT_EQ(vulnerabilityDescription->description()->str(), "not defined");
    EXPECT_EQ(vulnerabilityDescription->classification()->str(), "");
    EXPECT_EQ(vulnerabilityDescription->reference()->str(), "https://security.archlinux.org/CVE-2022-1154");
}

TEST_F(UpdateCVEDescriptionTest, RejectedCVE5Entry)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_REJECTED_CVE.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_REJECTED_CVE.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    ASSERT_FALSE(rocksDBWrapper->get(CVE_JSON_STR_REJECTED_CVE, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));
}

TEST_F(UpdateCVEDescriptionTest, RemoveDescription)
{
    std::string cve5FlatbufferSchemaStr;

    // Read schemas from filesystem.
    bool valid = (flatbuffers::LoadFile(CVE5_FLATBUFFER_SCHEMA_PATH.c_str(), false, &cve5FlatbufferSchemaStr));
    ASSERT_EQ(valid, true);
    ASSERT_EQ(JSON_STR_CVSS_V3_1.empty(), false);

    // Parse schemas and JSON example.
    flatbuffers::Parser parser;
    valid = (parser.Parse(cve5FlatbufferSchemaStr.c_str(), INCLUDE_DIRECTORIES) &&
             parser.Parse(JSON_STR_CVSS_V3_1.c_str()));
    ASSERT_EQ(valid, true);

    // Get flatbuffer pointer
    uint8_t* buf = parser.builder_.GetBufferPointer();
    size_t flatbufferSize = parser.builder_.GetSize();

    // Verify flatbuffer.
    flatbuffers::Verifier verifierCVE5(buf, flatbufferSize);
    ASSERT_EQ(cve_v5::VerifyEntryBuffer(verifierCVE5), true);
    const cve_v5::Entry* cve5Flatbuffer = cve_v5::GetEntry(buf);

    // Call function.
    std::unique_ptr<Utils::RocksDBWrapper> rocksDBWrapper = std::make_unique<Utils::RocksDBWrapper>(DATABASE_PATH);
    UpdateCVEDescription::storeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());

    // Get flatbuffer from vulnerability description database.
    std::string vulnerabilityDescriptionFBStr;
    EXPECT_TRUE(rocksDBWrapper->get(CVE_JSON_STR_CVSS_V3_1, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));

    // Remove entry and verify
    UpdateCVEDescription::removeVulnerabilityDescription(cve5Flatbuffer, rocksDBWrapper.get());
    EXPECT_FALSE(rocksDBWrapper->get(CVE_JSON_STR_CVSS_V3_1, vulnerabilityDescriptionFBStr, DESCRIPTIONS_COLUMN));
}
